﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using dal;
using System.Data;
using System.Collections;
using entity;
using DAL;
using System.Text.RegularExpressions;

/// <summary>
///BBSBBL 的摘要说明
/// </summary>
public class BBSBLL
{
    #region 论坛精华
    public string Imort(int count = 1)
    {
        BBSDAL bbsdal = new BBSDAL();
        string[][] tids = new string[][] { 
            new string[] { "13688", "胡俍观点" }, 
            new string []{"13687","方达点睛"},
            new string []{"13686","布衣解盘"},
            new string [] {"13909","曹茂桂"},
            new string []{"13908","顾勇菁"}

        };
        ArrayList lst = new ArrayList();
        for (int i = 0; i < tids.Length; i++)
        {
            DataTable tb = bbsdal.GeteData(tids[i][0], count);
            List<NewsEntity> tempLst = new List<NewsEntity>();

            foreach (DataRow row in tb.Rows)
            {
                NewsEntity temp = new NewsEntity();
                temp.Author = row["author"].ToString();
                temp.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
                temp.Title = row["subject"].ToString();
                temp.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
                tempLst.Add(temp);
            }
            lst.Add(new { name = tids[i][1], lst = tempLst });
        }
        return Newtonsoft.Json.JsonConvert.SerializeObject(lst);
    }

    public List<NewsEntity> Get名师解盘(int count = 6)
    {
        BBSDAL bbsdal = new BBSDAL();
        string[][] tids = new string[][] { 
                 new string[] { "13688", "胡俍观点" }, 
            new string []{"13687","方达点睛"},
            new string []{"13686","布衣解盘"},
            new string [] {"13798","天涯看盘"},
            new string []{"13908","顾勇菁"},
            new string []{"13909","曹茂桂"},
            new string [] {"13910","刘哲"},
            new string []{"13911","张程"}
            //new string []{"13912","顾旭明"},
            //new string []{"13915","何燕华"}
        };
        List<NewsEntity> lst = new List<NewsEntity>();
        for (int i = 0; i < tids.Length; i++)
        {
            DataTable tb = bbsdal.GeteData(tids[i][0], count);
            foreach (DataRow row in tb.Rows)
            {
                NewsEntity temp = new NewsEntity();
                temp.Id = Tools.GetLong(row["tid"]);
                temp.Author = tids[i][1];
                temp.ImageUrl = "http://bbs.emoney.cn/forum-" + tids[i][0] + "-1.html";
                temp.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
                temp.Title = row["subject"].ToString();
                temp.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
                lst.Add(temp);
            }
        }
        var tt = lst.OrderByDescending(x => x.PTime).Take(count).ToList();
        return tt;
    }

    public List<NewsEntity> GetListByType(string typeId, int count)
    {
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GeteData(typeId, count);
        List<NewsEntity> lst = new List<NewsEntity>();
        foreach (DataRow row in tb.Rows)
        {
            NewsEntity temp = new NewsEntity();
            temp.Id = Tools.GetLong(row["tid"]);
            temp.Author = row["author"].ToString();
            temp.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
            temp.Title = row["subject"].ToString();
            temp.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
            lst.Add(temp);
        }
        return lst;
    }

    /// <summary>
    /// 多少小时内热贴
    /// </summary>
    /// <param name="h">为负整数</param>
    /// <returns></returns>
    public List<NewsEntity> GetHotList(int h)
    {
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GetHots(h);
        List<NewsEntity> lst = new List<NewsEntity>();
        foreach (DataRow row in tb.Rows)
        {
            NewsEntity temp = new NewsEntity();
            temp.Id = Tools.GetLong(row["tid"]);
            temp.Author = row["author"].ToString();
            temp.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
            temp.Title = row["subject"].ToString();
            temp.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
            lst.Add(temp);
        }
        return lst;
    }

    public List<NewsEntity> 论坛精华()
    {
        List<NewsEntity> lst = new List<NewsEntity>();
        BBSDAL dal = new BBSDAL();
        DataTable tb = dal.Get论坛精华();
        List<NewsEntity> tempLst = new List<NewsEntity>();

        foreach (DataRow row in tb.Rows)
        {
            NewsEntity temp = new NewsEntity();
            temp.Author = row["author"].ToString();
            temp.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
            temp.Title = row["subject"].ToString();
            temp.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
            lst.Add(temp);
        }

        lst = lst.OrderByDescending(x => x.PTime).ToList();
        return lst;
    }

    public List<NewsEntity> 学习资料下载()
    {
        string id = "13706";
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GeteData(id, 20);
        List<NewsEntity> tempLst = new List<NewsEntity>();
        foreach (DataRow row in tb.Rows)
        {
            NewsEntity temp = new NewsEntity();
            temp.Author = row["author"].ToString();
            temp.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
            temp.Title = row["subject"].ToString();
            temp.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
            tempLst.Add(temp);
        }
        return tempLst;
    }

    public string Get帖子(string[] tids)
    {
        if (tids == null || tids.Length == 0)
        {
            tids = new string[] { "13688", "13687", "13798", "13686" };
        }
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.Get板块表(tids);
        ArrayList arr = new ArrayList();
        for (int i = 0; i < tb.Rows.Count; i++)
        {
            DataRow row = tb.Rows[i];
            string fid = Tools.GetString(row["fid"]);
            string name = Tools.GetString(row["name"]);
            int threads = Tools.GetInt(row["threads"]).Value;
            int posts = Tools.GetInt(row["posts"]).Value;
            int todayposts = Tools.GetInt(row["todayposts"]).Value;
            string tid = Tools.GetString(row["lastpost"]).Split('\t')[0];
            string lastpost = Tools.GetString(row["lastpost"]).Split('\t')[1];
            arr.Add(new
            {
                fid = fid,
                name = name,
                threads = threads,
                posts = posts,
                todayposts = todayposts,
                tid = tid,
                lastpost = lastpost
            });
        }
        return JsonBLL.ToJson(arr);
    }

    public string GetContents(long tid)
    {
        string key = "BBS_Contents_" + tid;
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GetContents(tid);
        NewsEntity news = null;
        if (tb.Rows.Count > 0)
        {
            var row = tb.Rows[0];
            news = new NewsEntity();
            news.Id = Tools.GetLong(row["tid"]);
            news.Title = Tools.GetString(row["subject"]);
            news.Author = Tools.GetString(row["author"]);
            news.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
            news.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
            news.Content = Tools.GetString(row["message"]);



            BBS_Post post = new BBS_Post();
            post.Allowhtml = Tools.GetInt(row["htmlon"]).Value;
            post.Bbcodeoff = Tools.GetInt(row["Bbcodeoff"]).Value;
            post.Sdetail = Tools.GetString(row["message"]);

            news.Content = UBBTools.UBBToHTML(post);
            news.Content = Regex.Replace(news.Content, "</tr>((?!<tr>).)*<tr>", "</tr><tr>");
            news.Content = Regex.Replace(news.Content, "\\[attach\\]((?!\\[/attach\\]).)*\\[/attach\\]", RmAttachment);

        }
        if (news != null)
        {
            str = JsonBLL.ToJson(news);
            MemcachedTools.Add(key, str, DateTime.Now.AddMinutes(30));
            return str;

        }
        else
        {
            return "{}";
        }
    }

    public DataRow GetAttachment(long aid)
    {
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GetAttachment(aid);
        if (tb.Rows.Count > 0)
        {
            return tb.Rows[0];
        }
        else
        {
            return null;
        }
    }



    static string RmAttachment(Match m)
    {
        try
        {
            string aa = m.Value;
            aa = aa.Replace("[attach]", "").Replace("[/attach]", "");
            long aid = long.Parse(aa);
            aa = Convert.ToBase64String(System.Text.Encoding.GetEncoding("GB2312").GetBytes(aa));
            BBSBLL bll = new BBSBLL();
            System.Data.DataRow row = bll.GetAttachment(aid);
            int isimage = DAL.Tools.GetInt(row["isimage"]).Value;
            if (isimage == 1)
            {
                int width = DAL.Tools.GetInt(row["width"]).Value;
                if (width > 600)
                {
                    width = 600;
                }
                string strWidth = width == 0 ? "" : "width=\"" + width + "\"";
                string url = "http://bbs.emoney.cn/forum.php?mod=attachment&aid=" + aa + "&noupdate=yes";
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<p align=\"center\">");
                sb.Append("<img src=\"http://bbs.emoney.cn/forum.php?mod=attachment&aid=" + aa + "\" alt=\"\"" + strWidth + " />");
                sb.Append("</p>");
                return sb.ToString(); ;
            }
            else
            {
                return "";
            }
        }
        catch
        {
            return "";
        }
    }
    #endregion

    #region 通用
    public string GetForumById(int fid, int count)
    {
        string key = "BBS_Contents_Forum_" + fid;
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GetContentsByFid(fid, count);
        List<NewsEntity> newslist = new List<NewsEntity>();

        if (tb.Rows.Count > 0)
        {
            NewsEntity news = null;
            var row = tb.Rows[0];
            news = new NewsEntity();
            news.Id = Tools.GetLong(row["tid"]);
            news.Title = Tools.GetString(row["subject"]);
            news.Author = Tools.GetString(row["author"]);
            news.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
            news.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
            news.Content = Tools.GetString(row["message"]);



            BBS_Post post = new BBS_Post();
            post.Allowhtml = Tools.GetInt(row["htmlon"]).Value;
            post.Bbcodeoff = Tools.GetInt(row["Bbcodeoff"]).Value;
            post.Sdetail = Tools.GetString(row["message"]);

            news.Content = UBBTools.UBBToHTML(post);
            news.Content = Regex.Replace(news.Content, "</tr>((?!<tr>).)*<tr>", "</tr><tr>");
            news.Content = Regex.Replace(news.Content, "\\[attach\\]((?!\\[/attach\\]).)*\\[/attach\\]", RmAttachment);

            newslist.Add(news);

        }
        if (newslist.Count > 0)
        {
            str = JsonBLL.ToJson(newslist);
            MemcachedTools.Add(key, str, DateTime.Now.AddMinutes(30));
            return str;

        }
        else
        {
            return "{}";
        }
    }
    #endregion



    public string GeteDataByTypeid(int typeid, int count)
    {
        try
        {
            string key = "BBS_Contents_Forum_Tid_" + typeid + "_count_" + count;
            string str = (string)MemcachedTools.Get(key);
            if (!string.IsNullOrEmpty(str))
            {
                return str;
            }
            BBSDAL bbsdal = new BBSDAL();
            DataTable tb = bbsdal.GeteDataByTypeid(typeid, count);

            List<NewsEntity> newslist = new List<NewsEntity>();

            if (tb.Rows.Count > 0)
            {
                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    NewsEntity news = null;
                    var row = tb.Rows[i];
                    news = new NewsEntity();
                    news.Id = Tools.GetLong(row["tid"]);
                    news.Title = Tools.GetString(row["subject"]);
                    news.Author = Tools.GetString(row["author"]);
                    news.PTime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
                    news.Url = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
                    newslist.Add(news);
                }
            }
            if (newslist.Count > 0)
            {
                str = JsonBLL.ToJson(newslist);
                MemcachedTools.Add(key, str, DateTime.Now.AddMinutes(30));
                return str;
            }
            else
            {
                return null;
            }
        }
        catch
        {
            return string.Empty;
        }
    }


}